// ==========================================================================
// gin-sns自动生成业务逻辑层相关代码，只生成一次，按需修改,再次生成不会覆盖.
// date：2021-02-21 13:45:54 +0800 CST
// path: app/service/module/like_service.go
// author：jon
// ==========================================================================
package module

import (
	"errors"

	"gin-sns/app/dao/module/like"
	"gin-sns/app/dao/module/user"
	"gin-sns/app/model"
	"gin-sns/app/model/constants"
	likeModel "gin-sns/app/model/module/like"
	"gin-sns/app/service/render"
	"time"

	"github.com/gin-gonic/gin"

	"gin-sns/app/ginframe/utils/convert"
	"gin-sns/app/ginframe/utils/page"
)

var LikeService = newLikeService()

func newLikeService() *likeService {
	return &likeService{}
}

type likeService struct {
}

//根据主键查询数据
func (s *likeService) SelectRecordById(id int64) (*likeModel.Entity, error) {
	return like.LikeDao.SelectById(id)
}

//
func (s *likeService) SelectRecordsIn(idarr []int64) ([]likeModel.Entity, error) {

	list, err := like.LikeDao.FindIn("id", idarr)
	if list != nil && len(list) > 0 {
		err = errors.New("not found")
		list = nil
	}
	return list, err
}

//根据主键删除数据
func (s *likeService) DeleteRecordById(id int64) bool {
	return like.LikeDao.DeleteById(id)
}

//批量删除数据记录
func (s *likeService) DeleteRecordByIds(ids string) int64 {
	ida := convert.ToInt64Array(ids, ",")
	result, err := like.LikeDao.DeleteBatch(ida...)
	if err != nil {
		return 0
	}
	return result
}

//添加数据
func (s *likeService) AddSave(req *likeModel.AddReq, ctx *gin.Context) (int64, error) {
	var entity likeModel.Entity

	//entity.Id = req.Id
	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	entity.CreateTime = time.Now()
	//entity.CreateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user != nil {
	//	entity.CreateBy = user.LoginName
	//}

	_, err := like.LikeDao.Insert(&entity)
	return entity.Id, err
}

//修改数据
func (s *likeService) EditSave(req *likeModel.EditReq, ctx *gin.Context) (int64, error) {
	entity := &likeModel.Entity{Id: req.Id}
	ok, err := like.LikeDao.FindOne(entity)

	if err != nil {
		return 0, err
	}

	if !ok {
		return 0, errors.New("数据不存在")
	}

	entity.UserId = req.UserId
	entity.EntityType = req.EntityType
	entity.EntityId = req.EntityId
	entity.Status = req.Status
	//entity.UpdateTime = time.Now()
	//entity.UpdateBy = ""

	//user := system.UserService.GetProfile(ctx)

	//if user == nil {
	//	entity.UpdateBy = user.LoginName
	//}

	return like.LikeDao.Update(entity)
}

//根据条件查询数据
func (s *likeService) SelectListAll(params *likeModel.SelectPageReq) ([]likeModel.Entity, error) {
	return like.LikeDao.SelectListAll(params)
}

//根据条件分页查询数据
func (s *likeService) SelectListByPage(params *likeModel.SelectPageReq) ([]likeModel.Entity, *page.Paging, error) {
	return like.LikeDao.SelectListByPage(params)
}

// 导出excel
func (s *likeService) Export(param *likeModel.SelectPageReq) (string, error) {
	head := []string{"", "用户id", "实体类型", "实体id", "0未审核 1正常状态 2审核未通过 3删除", "添加时间"}
	col := []string{"id", "user_id", "entity_type", "entity_id", "status", "create_time"}
	return like.LikeDao.SelectListExport(param, head, col)
}

// 统计数量
func (s *likeService) CountPostLike(id int64) int64 {

	return like.LikeDao.Count(constants.EntityTypePost, id)
}

// 最近点赞
func (s *likeService) GetRecent(entityType int, entityId int64, count int) []likeModel.Entity {
	list, err := like.LikeDao.GetNewestLikes(entityType, entityId, count)
	if err != nil {
		return nil
	}

	return list
}

func (s *likeService) CountArticleLike(id int64) int64 {

	return like.LikeDao.Count(constants.EntityTypeArticle, id)
}

func (s *likeService) CountCommentLike(id int64) int64 {

	return like.LikeDao.Count(constants.EntityTypeComment, id)
}

func (s *likeService) Like(userId int64, postId int64) error {
	post, _ := PostService.SelectRecordById(postId)
	if post == nil || post.Status != model.PostStatusOk {
		return errors.New("话题不存在")
	}

	// 判断是否已经点赞了
	if s.Exists(userId, constants.EntityTypePost, postId) {
		return errors.New("已点赞")
	}

	// 点赞
	entity := &likeModel.Entity{
		UserId:     userId,
		EntityId:   postId,
		EntityType: constants.EntityTypePost,
		CreateTime: time.Now(),
	}

	_, err := like.LikeDao.Insert(entity)
	if err != nil {
		return err
	}

	// 更新帖子点赞数
	PostService.IncrLikeCount(postId)
	return nil

}

// 统计数量
func (s *likeService) Count(entityType int, entityId int64) int64 {

	return like.LikeDao.Count(entityType, entityId)

}

// 最近点赞
func (s *likeService) GetRecentUsers(entityType int, entityId int64, count int) []model.UserInfo {
	likes, _ := like.LikeDao.GetNewestLikes(entityType, entityId, count)

	var users []model.UserInfo
	for _, like := range likes {
		//userInfo := render.BuildUserById(like.UserId)
		user, err := user.UserDao.SelectById(like.UserId)
		if err == nil && user != nil {
			userInfo := render.BuildUser(user)

			if userInfo != nil {
				users = append(users, *userInfo)
			}
		}
	}

	return users
}

// Exists 是否点赞
func (s *likeService) Exists(userId int64, entityType int, entityId int64) bool {

	entity := &likeModel.Entity{
		UserId:     userId,
		EntityType: entityType,
		EntityId:   entityId,
	}

	have, _ := like.LikeDao.FindOne(entity)

	return have

}

// 是否点赞，返回已点赞实体编号
func (s *likeService) IsLiked(userId int64, entityType int, entityIds []int64) []int64 {

	return like.LikeDao.IsLiked(userId, entityType, entityIds)
}

// 话题点赞
func (s *likeService) ArticleLike(userId int64, articleId int64) error {
	article, _ := ArticleService.SelectRecordById(articleId)
	if article == nil || article.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if err := s.like(userId, constants.EntityTypeArticle, articleId); err != nil {
		return err
	}

	// 更新点赞数
	ArticleService.IncrLikeCount(articleId)

	// 发送消息
	MessageService.SendPostLikeMsg(articleId, userId)

	return nil
}

func (s *likeService) CancelArticleLike(userId int64, articleId int64) error {
	article, _ := ArticleService.SelectRecordById(articleId)
	if article == nil || article.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if !s.Exists(userId, constants.EntityTypeArticle, articleId) {
		return nil
	}

	if err := s.cancel_like(userId, constants.EntityTypeArticle, articleId); err != nil {
		return err
	}

	// 更新点赞数
	ArticleService.DecrLikeCount(articleId)

	// 发送消息
	//messageService.SendPostLikeMsg(postId, userId)

	return nil
}

//
// 话题点赞
func (s *likeService) PostLike(userId int64, postId int64) error {
	post, _ := PostService.SelectRecordById(postId)
	if post == nil || post.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if err := s.like(userId, constants.EntityTypePost, postId); err != nil {
		return err
	}

	// 更新点赞数
	PostService.IncrLikeCount(postId)

	// 发送消息
	MessageService.SendPostLikeMsg(postId, userId)

	return nil
}

func (s *likeService) CancelPostLike(userId int64, postId int64) error {
	post, _ := PostService.SelectRecordById(postId)
	if post == nil || post.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if !s.Exists(userId, constants.EntityTypePost, postId) {
		return nil
	}

	if err := s.cancel_like(userId, constants.EntityTypePost, postId); err != nil {
		return err
	}

	// 更新点赞数
	PostService.DecrLikeCount(postId)

	// 发送消息
	//messageService.SendPostLikeMsg(postId, userId)

	return nil
}

//
// 话题点赞
func (s *likeService) CommentLike(userId int64, commentId int64) error {
	comment, _ := CommentService.SelectRecordById(commentId)
	if comment == nil || comment.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if err := s.like(userId, constants.EntityTypeComment, commentId); err != nil {
		return err
	}

	// 更新点赞数
	CommentService.IncrLikeCount(commentId)

	// 发送消息
	MessageService.SendCommentLikeMsg(commentId, userId)

	return nil
}

func (s *likeService) CancelCommentLike(userId int64, commentId int64) error {
	comment, _ := CommentService.SelectRecordById(commentId)
	if comment == nil || comment.Status != constants.StatusOk {
		return errors.New("话题不存在")
	}

	if !s.Exists(userId, constants.EntityTypeComment, commentId) {
		return nil
	}

	if err := s.cancel_like(userId, constants.EntityTypeComment, commentId); err != nil {
		return err
	}

	// 更新点赞数
	CommentService.DecrLikeCount(commentId)

	// 发送消息
	//messageService.SendCommentLikeMsg(commentId, userId)

	return nil
}

func (s *likeService) like(userId int64, entityType int, entityId int64) error {
	// 判断是否已经点赞了
	if s.Exists(userId, entityType, entityId) {
		return errors.New("已点赞")
	}
	// 点赞
	entity := &likeModel.Entity{
		UserId:     userId,
		EntityType: entityType,
		EntityId:   entityId,
		CreateTime: time.Now(),
	}

	_, err := like.LikeDao.Insert(entity)

	return err
}

func (s *likeService) cancel_like(userId int64, entityType int, entityId int64) error {
	// 判断是否已经点赞了
	if s.Exists(userId, entityType, entityId) {
		//return errors.New("已点赞")
		// 点赞
		entity := &likeModel.Entity{
			UserId:     userId,
			EntityType: entityType,
			EntityId:   entityId,
			//CreateTime: time.Now(),
		}
		_, err := like.LikeDao.FindOne(entity) //find

		_, err = like.LikeDao.Delete(entity) //delete
		return err
	}

	return nil
}
